import { JXDef } from "../../../conventions/JXCommon";
import GChild from "../../../Core/GView/GChild";
import { AudioMgr } from "../../../Core/Manager/AudioMgr";
import TyqEventMgr from "../../../tyq/tyq-event-mgr";
import { CMsg } from "../../Common/Define";
import { L } from "../../Common/Language";
import { VIEW_ID } from "../../Common/UI";
import { Res } from "../../Common/UIResources";
import { JXLocales } from "../../Common/Zh";
import BtlHeroHead from "../../Views/Fight/BtlHeroHead";
import { JXBtlPs } from "../../Views/JXBattle/JXBattleDefine";
import JXBtlMgr from "../../Views/JXBattle/JXBattleManager";
import JXRBCmdMgr from "../../Views/JXBattle/JXRBCmdMgr";
import GameMgr from "../GameMgr";
import { GCtrl } from './../../../Core/GCtrl';
import { PART_BTL_SCENE } from './../../Common/Define';

const { ccclass, property, menu } = cc._decorator;

@ccclass
export default class BtlFightLayer extends GChild {
	@property(cc.Node) wheatNode: cc.Node = null;
	@property(cc.Node) heroContent: cc.Node = null;
	@property(cc.Label) level: cc.Label = null;
	@property(cc.Label) bool: cc.Label = null;
	/**公共的命令管理类 */
	private _cmdMgr: JXRBCmdMgr;
	private _secenId: number = null;

	private _btlReport: BattleInfo<IMonsterBtl, IMonsterBtl> = null;
	public _cbFun: Function = null;
	public winArgs: ArgsBattleViewCtrl<any> = null;
	private _level: SStoryDataRaw | STowerDataRaw = null;
	public logicAni: cc.Tween[] = null;
	public mapRaw: SMapDataRaw = null;


	/**初始战斗层 */
	public fightInit(winArgs: ArgsBattleViewCtrl<any>, cb) {
		this._secenId = winArgs.sceneId;
		this.winArgs = winArgs;
		this._cbFun = cb;
		/*第一第二第三关在引导未结束的时候不进行营销 */
		if ((winArgs.args.level === 1 || winArgs.args.level === 2 || winArgs.args.level === 3) && !GameMgr.lUserData.isDoneGuide()) {
			this.loadEnv()
		} else {
			let render = Math.random();
			if (render <= 0.5) {
				GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.heroTry, () => {
					this.loadEnv();
				})
			} else {
				// GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.openBox, () => {
				// 	this.loadEnv();
				// })
				GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.heroTry, () => {
					this.loadEnv();
				})
			}

		}
	}

	update() {
		if (!this._cmdMgr) return;
		this._cmdMgr.update();
	}

	/**根据场景id加载对应数据 */
	protected loadEnv() {
		switch (this._secenId) {
			case PART_BTL_SCENE.GUANQIA: {
				let tpl = this.winArgs as ArgsBattleViewCtrl<SceneGuanQia>;
				// GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.battle, { msg: L(JXLocales.tower.level, tpl.args.level) })
				if (tpl.args.level == 4) {
					GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.level4, { msg: L(JXLocales.tower.level, tpl.args.level) })
				}
				this._level = GameMgr.storyData.getRaw<SStoryDataRaw>(tpl.args.level);
				this.mapRaw = GameMgr.mapData.getRaw<SMapDataRaw>(this._level.mapld);
				this._btlReport = GameMgr.rHeroData.createRespWithRealData(this._level)
				this.level.string = L(JXLocales.tower.level, this._level.id)
				TyqEventMgr.ins.onStartGame(100000 + this._level.id);
				break;
			}
			case PART_BTL_SCENE.ARENA: {
				let tpl = this.winArgs as ArgsBattleViewCtrl<SceneGuanQia>;

				this._level = GameMgr.towerData.getRaw<STowerDataRaw>(tpl.args.level);
				this.mapRaw = GameMgr.mapData.getRaw<SMapDataRaw>(this._level.mapld);
				this._btlReport = GameMgr.rHeroData.createRespWithRealData(this._level)
				this.level.string = L(JXLocales.tower.level, this._level.id)
				TyqEventMgr.ins.onStartGame(200000 + this._level.id);
			}
		}
		this._btlReport.random = GCtrl.now.toString();
		console.log("实际战报详情", this._btlReport)
		this._cmdMgr = new JXRBCmdMgr(this._secenId, "RBBattle", this._level.id);
		this._cmdMgr.initRDBtlLayer(this.node);
		// 注册战斗事件
		this._cmdMgr.evtMgr.register(CMsg.client.fight_ui.end_fight, this, this.onEndFight.bind(this));
		this._cmdMgr.jxBtlAns = JXBtlMgr.ins.fight(this._btlReport.atker, this._btlReport.defer, this._cmdMgr);
		this._cmdMgr.jxBtlAns.setBarrackHps(this._level.hp, this.bool);
		this.bool.string = L(JXLocales.fight.bool, this._level.hp);
		this._cmdMgr.monsterCtrl = () => {
			this.setLogicAni(this.mapRaw.logic, () => {
				this._cmdMgr.monsterFactory.init(this._btlReport.atker.ext, this.mapRaw.logic, this._cmdMgr, this.logicAni);
				this._cmdMgr.monsterFactory.startProduce();
				this._cmdMgr._wave.string = L(JXLocales.fight.wave, this._cmdMgr.monsterFactory.waveNum + 1);

				this.scheduleOnce(() => {
					this._cmdMgr.monsterFactory.startRoadAni();
				}, 0.5)
			});
		}
		this._cmdMgr.loadAllResources(this.onResLoaded.bind(this));
		return this._cmdMgr;
	}

	protected setLogicAni(roads: any[][], cb) {
		this.assetImpl.prefab(Res.prefab.item.jxRoadPoint, (prefab: cc.Prefab) => {
			this.logicAni = []
			roads.forEach((road: number[]) => {
				let point = cc.instantiate(prefab);
				point.parent = this.node;
				let fristPos = GameMgr.mapMgr.decodeXxyy(road[0]);
				let fristPosition = this._cmdMgr.btlMapConverts.converToCCPos(fristPos);
				point.position = fristPosition;
				let tween1 = cc.tween(point);
				let tween2 = cc.tween(point).call(() => {
					point.active = true;
					tween1.start();
				})
				road.forEach(id => {
					let pos = GameMgr.mapMgr.decodeXxyy(id);
					let position = this._cmdMgr.btlMapConverts.converToCCPos(pos);
					tween1.to(0.2, { position: position })
				})
				tween1.call(() => {
					point.active = false;
					point.position = fristPosition;
				})
				this.logicAni.push(tween2);
			})
			cb();
		})
	}

	/**战斗结束*/
	protected onEndFight() {

		let info = {
			sceneId: this._secenId,
			isWin: this._cmdMgr.jxBtlAns.isDefWin
		}
		if (info.isWin) {
			AudioMgr.Ins().playEffect(Res.audio.nextWave);
		}

		this.scheduleOnce(() => {
			GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.battleResult, this._secenId, this._level.id, this._cmdMgr.jxBtlAns, () => {
				GCtrl.ES.emit(CMsg.client.fight_ui.onFinishSettle, info)
			});
		}, 2)
	}

	onResLoaded() {
		if (!this.isValid) return;
		this.initBattleHead();
		this._cbFun(this._cmdMgr);
	}

	protected initBattleHead() {
		this.heroContent.destroyAllChildren();
		this.assetImpl.prefab(Res.prefab.vw.fight.head, (Prefab) => {
			let def = this._btlReport.defer;
			for (let i = 0; i < def.partnerData.length; i++) {
				let hero = def.partnerData[i];
				if (hero.heroId != JXBtlPs.InvalidString) {
					let node = cc.instantiate(Prefab);
					let comp = node.getComponent(BtlHeroHead);
					comp.init(hero, this._cmdMgr);
					comp.setSeatNode(this.node);
					this.heroContent.addChild(node)
				}
			}
		})
	}

	onGDestroy() {
		if (this._cmdMgr) {
			this._cmdMgr.monsterFactory.destory();
			this._cmdMgr.pause();
			this._cmdMgr.destroy();
			this._cmdMgr = null;
		}
	}
}